package UpLoadFile;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-22
 * Time: 19:56
 */
@MultipartConfig
@WebServlet("/upLoadFile")
public class UpLoadFile extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //构造Post请求来上传文件
        //获取请求中给定MyFile的文件
        Part part = req.getPart("MyFile");
        //获取到文件的名字
        String cd = part.getHeader("Content-Disposition");
        //截取不同类型的文件需要自行判断
        String filename = cd.substring(cd.lastIndexOf("=")+2, cd.length()-1);
        System.out.println(filename);
        //获取到文件的大小
        System.out.println(part.getSize());
        //获取到文件的格式
        System.out.println(part.getContentType());
        //将文件写到本地磁盘上
        part.write("d:/result.jpg");
        resp.getWriter().write("upload : ok");
    }

}
